﻿using UnityEngine;
using System.Collections;

public class scPigAction : MonoBehaviour {

	public const float pigStandardHP = 50.0f;
	public GameObject pigCrash;
	
	enum PigCondition
	{
		con1 = 1,
		con2,

		Count
	}
	
	private float pigHP = pigStandardHP;
	private bool isDamageSafe = true;
	private Animator anim;
	private GameObject gameManager;

	
	// Use this for initialization
	void Start () {
		gameManager = GameObject.Find("GameManager");

		rigidbody2D.collider2D.isTrigger = false;
		
		anim = GetComponent<Animator>();
		
		StartCoroutine(_AnimationTimer(0.5f));
		
		Invoke("_VitalizeDamage", 1.0f);
	}
	
	// Update is called once per frame
	void Update () {
	}
	
	void OnCollisionEnter2D(Collision2D coll)
	{
		if (isDamageSafe)
		{
			return;
		}

		if (coll.gameObject.tag == "Bird")
		{
			return;
		}
		else if (coll.gameObject.tag == "Block" || coll.gameObject.tag == "Pig")
		{
			_DamageToAnothers(coll);
		}
		else
		{
			_SelfDamage();
		}
	}

	void ApplyDamage(float damage)
	{
		pigHP -= damage;
		
		_SetPigStatusAnimation();

		if (pigHP <= 0f)
		{
			GameObject crashEffect = (GameObject)Instantiate(pigCrash, transform.position, Quaternion.Euler(0f, 0f, 0f));
			
			Animator anim = crashEffect.GetComponent<Animator>();
			anim.SetTrigger("WhiteCrash");
			
			DestroyObject(gameObject);

			scGameManager.AddScore(5000);
			gameManager.SendMessage("DiedPig");
		}
	}

	void _VitalizeDamage()
	{
		isDamageSafe = false;
	}

	void _DamageToAnothers(Collision2D coll)
	{
		float hitDamage = Mathf.Max(pigHP / 2.0f, 1f);
		
		coll.gameObject.SendMessage("ApplyDamage", hitDamage, SendMessageOptions.DontRequireReceiver);
	}
	
	void _SelfDamage()
	{
		float hitDamage = Mathf.Max(pigHP / 2.0f, 1f);
		
		ApplyDamage(hitDamage);
	}

	IEnumerator _AnimationTimer(float delayTime)
	{
		yield return new WaitForSeconds(delayTime);
		
		_SetPigStatusAnimation();
			
		StartCoroutine(_AnimationTimer(Random.Range(2.0f, 4.0f)));
	}
	
	void _SetPigStatusAnimation()
	{
		PigCondition condition = (PigCondition)Random.Range((int)PigCondition.con1, (int)PigCondition.Count);
		anim.SetInteger("PigCondition", (int)condition);

		if (pigHP >= pigStandardHP)
		{
			anim.SetTrigger("PigIdle");
		}
		else if (pigHP > 0.6f * pigStandardHP)
		{
			anim.SetTrigger("PigCracked");
		}
		else
		{
			anim.SetTrigger("PigPoor");
		}
	}
}
